//
//  APIService+Login.m
//  JiZhuiAn
//
//  Created by roger lin on 16/6/20.
//  Copyright © 2016年 Easy. All rights reserved.
//

#import "APIService+Login.h"

@implementation APIService (Login)

- (RACSignal *)loginWithPhoneNumber:(NSString *)phoneNumber
                           Password:(NSString *)password
{
   return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {

        [BmobUser loginWithUsernameInBackground:phoneNumber password:password block:^(BmobUser *user, NSError *error) {
            if (user) {
                NSLog(@"登录成功");
                EVBmobUser *newUser = [[EVBmobUser alloc]initFromBmobObject:user];
                self.user = newUser;
                [subscriber sendNext:@(1)];
                [subscriber sendCompleted];
            }
            else
            {
                [subscriber sendError:error];
            }
        }];
       return nil;
    }];
}

- (RACSignal *)getSpineTestData
{
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        if (self.user.hadSpineTested) {
            BmobQuery * query = [BmobQuery queryWithClassName:@"SpineTest"];
            [query whereKey:@"userId" equalTo:self.user.objectId];
            [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
                if (!error) {
                    if (array.count == 0) {
                        return ;
                    }
                    BmobObject * object = array[0];
                    self.spineTestData = [[SpineTestData alloc] initFromBmobObject:object];
                }
            }];
        }
        else {
            SpineTestData * data = [[SpineTestData alloc] init];
            data.neckPoint = 100;
            data.waistPoint = 100;
            data.kneePoint = 100;
            self.spineTestData = data;
        }
        return nil;
    }];
}

- (RACSignal *)logout
{
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [BmobUser logout];
        [subscriber sendNext:@1];
        [subscriber sendCompleted];
        return nil;
    }];
}

@end
